<?php


namespace app\xiangji\jobs;


use app\common\models\LoveScore;
use app\common\models\UserRecharge;
use app\xiangji\services\LoveScoreService;
use app\xiangji\services\PayService;
use app\xiangji\services\WechatService;
use Carbon\Carbon;
use think\facade\Log;
use think\queue\Job;

class WxPayOrderQueryJob
{
    private $payService;
    public function __construct(PayService $payService)
    {
        $this->payService = $payService;
    }
    public function fire(Job $job, string $out_trade_no)
    {
        try {
            // 重复次数不能超过3次
            if ($job->attempts() >= 3){
                $job->delete();
                return;
            }
            // 查询本地订单状态
            $recharge = UserRecharge::where('order_no', '=', $out_trade_no)->find();
            // 用户支付中，其余状态可关闭任务
            if ($recharge->status != UserRecharge::PAY_SUCCESS && $recharge->trade_state == 'USERPAYING'){
                $job->delete();
                return;
            }
            // 查询微信端订单信息
            $result = $this->payService->wechat()->queryWxPayByOutTradeNumber($out_trade_no);
            if ($result['return_code'] != 'SUCCESS'){
                // 通信失败
                $job->delete();
                return;
            }
            // 业务错误
            if ($result['result_code'] != 'SUCCESS'){
                // 订单有误
                $recharge->save([
                    'err_code'      => $result['err_code'],
                    'err_code_des'  => $result['err_code_des'],
                    'status'        => UserRecharge::PAY_FAIL
                ]);
                $job->delete();
                return;
            }
            // 交易状态trade_state不为 SUCCESS，则只返回out_trade_no（必传）和attach（选传）
            if ($result['trade_state'] != 'SUCCESS'){
                switch ($result['trade_state']){
                    case 'SUCCESS':
                        $pay_status = UserRecharge::PAY_SUCCESS;
                        break;
                    case 'PAYERROR':
                    case 'REVOKED':
                    case 'CLOSED':
                        $pay_status = UserRecharge::PAY_FAIL;
                        break;
                    default:
                        $pay_status = UserRecharge::PAY_NOTPAY;

                }
                $recharge->save([
                    'trade_state'   => $result['trade_state'],
                    'status'        => $pay_status
                ]);
                $job->delete();
                return;
            }
            // 正常支付成功返回记录结果
            $recharge->save([
                'status'            => UserRecharge::PAY_SUCCESS,
                'paid_fee'          => $result['total_fee'],
                'transaction_id'    => $result['transaction_id'],
                'trade_state'       => $result['trade_state'],
                'pay_time'          => strtotime($result['time_end']),
            ]);
            // 记录支付订单返回结果
            $recharge->log->save(['pay_result' => json_encode($result)]);
            // 已支付，更新订单信息，并关闭订单
            $this->payService->wechat()->closeWxPayOrder($out_trade_no);
            $job->delete();
            return true;
        }catch (\Exception $exception){
            $job->delete();
        }
    }
}
